﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Net.Sockets;
using System.Net;
using Org.Mentalis.Network.ProxySocket;
using System.Threading;
using __Able.Core.Utilities;
using __Able.Network.Utils;

namespace ConsoleApplication2
{
    class Program
    {
        private static Socket socket;
        private static Socket clientsock;
        private const int port = 8080;

        static void Main(string[] args)
        {
            socket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
            socket.Blocking = true;
            IPEndPoint computernode1 = new IPEndPoint(IPAddress.Parse("127.0.0.1"), port);
            socket.Bind(computernode1);
            socket.Listen(10);
            socket.BeginAccept(new AsyncCallback(OnArrived), socket);

            ConsoleAttributes.ForeColor = __Able.Core.Utilities.ConsoleColor.LightGreen;
            Console.WriteLine(string.Format("[port:{0}] CCU BeginReceive... ", port));
            ConsoleAttributes.ForeColor = __Able.Core.Utilities.ConsoleColor.Gray;
            Console.ReadKey();
        }

        public static void OnArrived(IAsyncResult ar)
        {
            Socket listener = (Socket)ar.AsyncState;
            clientsock = listener.EndAccept(ar);
            Console.WriteLine("Client {0}, joined", clientsock.RemoteEndPoint);
            //// Get current date and time. 
            //DateTime now = DateTime.Now;
            //string strDateLine = "Welcome " + now.ToString("G");
            //// Convert to byte array and send. 
            //Byte[] byteDateLine = System.Text.Encoding.ASCII.GetBytes(strDateLine.ToCharArray());
            //clientsock.Send(byteDateLine, byteDateLine.Length, 0);

            listener.BeginAccept(new AsyncCallback(OnArrived), listener);
        }
        private static byte[] receiveBuf = new byte[1024];
        protected static void BeginDataReceive(ProxySocket socket)
        {
            receiveBuf.Initialize();
            socket.BeginReceive(receiveBuf, 0, receiveBuf.Length, SocketFlags.None, new AsyncCallback(EndDataReceive), socket);
        }
        protected static void EndDataReceive(IAsyncResult ar)
        {
            int cnt = 0;
            try
            {
                ProxySocket socket = (ProxySocket)ar.AsyncState;
                cnt = socket.EndReceive(ar);
                if (cnt != 0)
                {
                    ByteBuffer byteBuffer = new ByteBuffer(receiveBuf, 0, cnt);
                    Console.WriteLine(Util.GetString(byteBuffer));
                    //创建一个新的字节对象
                    receiveBuf.Initialize();
                }
                BeginDataReceive(socket);
            }
            catch (Exception e)
            {
                Console.WriteLine(e.Message);
            }
        }
    }
}
